package com.deyou.activity;

import android.content.ContentValues;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deyou.Constants;
import com.deyou.R;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.event.LoginEvent;
import com.deyou.model.LzyResponse;
import com.deyou.model.UserInfoBean;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.Logger;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.SaveCallback;

import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_phone_label)
    ImageView ivPhoneLabel;
    @BindView(R.id.phone_login_layout)
    RelativeLayout phoneLoginLayout;
    @BindView(R.id.iv_mail_label)
    ImageView ivMailLabel;
    @BindView(R.id.mail_login_layout)
    RelativeLayout mailLoginLayout;
    @BindView(R.id.login_header_layout)
    RelativeLayout loginHeaderLayout;
    @BindView(R.id.tv_phone_title)
    TextView tvPhoneTitle;
    @BindView(R.id.tv_phone_area_code)
    TextView tvPhoneAreaCode;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.phone_layout)
    RelativeLayout phoneLayout;
    @BindView(R.id.tv_mail_title)
    TextView tvMailTitle;
    @BindView(R.id.et_mail)
    EditText etMail;
    @BindView(R.id.mail_layout)
    RelativeLayout mailLayout;
    @BindView(R.id.tv_pwd_title)
    TextView tvPwdTitle;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.password_layout)
    RelativeLayout passwordLayout;
    @BindView(R.id.btn_login)
    TextView btnLogin;
    @BindView(R.id.btn_regist)
    TextView btnRegist;
    @BindView(R.id.btn_forget_pwd)
    TextView btnForgetPwd;
    @BindView(R.id.tv_other_logintype)
    TextView tvOtherLogintype;
    @BindView(R.id.iv_login_by_wechat)
    ImageView ivLoginByWechat;
    @BindView(R.id.activity_login)
    LinearLayout activityLogin;
    @BindView(R.id.ic_nosee_pwd)
    ImageView icNoseePwd;

    private boolean flag = false;
    private int userLoginType = 2; // 1-手机登录 2-邮箱登录

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        flag = true;
        userLoginType = 2;
        etPhone.setText(SPUtils.getStringByKey(LoginActivity.this, Constants.PhoneUserName));
        etMail.setText(SPUtils.getStringByKey(LoginActivity.this, Constants.MailUserName));
    }

    @Override
    protected boolean translucentStatusBar() {
        return super.translucentStatusBar();
    }

    @OnClick({R.id.iv_back, R.id.phone_login_layout, R.id.mail_login_layout, R.id.tv_phone_area_code,
            R.id.btn_login, R.id.btn_regist, R.id.btn_forget_pwd, R.id.iv_login_by_wechat, R.id.ic_nosee_pwd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.phone_login_layout:
                ivPhoneLabel.setVisibility(View.VISIBLE);
                ivMailLabel.setVisibility(View.GONE);
                mailLayout.setVisibility(View.GONE);
                phoneLayout.setVisibility(View.VISIBLE);
                loginHeaderLayout.setBackgroundResource(R.drawable.bg_phone_login);
                etPassword.setText("");
                userLoginType = 1;
                etPhone.setText(SPUtils.getStringByKey(LoginActivity.this, Constants.PhoneUserName));
                break;
            case R.id.mail_login_layout:
                ivPhoneLabel.setVisibility(View.GONE);
                ivMailLabel.setVisibility(View.VISIBLE);
                mailLayout.setVisibility(View.VISIBLE);
                phoneLayout.setVisibility(View.GONE);
                loginHeaderLayout.setBackgroundResource(R.drawable.bg_mail_login);
                etPassword.setText("");
                userLoginType = 2;
                etMail.setText(SPUtils.getStringByKey(LoginActivity.this, Constants.MailUserName));
                break;
            case R.id.tv_phone_area_code:
                break;
            case R.id.btn_login:
                if (1 == userLoginType) {
                    if (TextUtils.isEmpty(etPhone.getText().toString().trim())) {
                        showToast("登录手机号不能为空");
                        return;
                    }
                } else if (2 == userLoginType) {
                    if (TextUtils.isEmpty(etMail.getText().toString().trim())) {
                        showToast("登录邮箱不能为空");
                        return;
                    }
                }
                if (TextUtils.isEmpty(etPassword.getText().toString().trim())) {
                    showToast("登录密码不能为空");
                    return;
                }
                loginInToApp();
                break;
            case R.id.btn_regist:
                AndroidUtils.startNextActivity(this, RegistActivity.class, null, false);
                break;
            case R.id.btn_forget_pwd:
                AndroidUtils.startNextActivity(this, ForgetPwdActivity.class, null, false);
                break;
            case R.id.iv_login_by_wechat:
                break;
            case R.id.ic_nosee_pwd:
                if (TextUtils.isEmpty(etPassword.getText().toString().trim()))
                    return;
                if (flag == true) {
                    etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    flag = false;
                    icNoseePwd.setImageResource(R.drawable.ic_see_pwd);
                } else {
                    etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    flag = true;
                    icNoseePwd.setImageResource(R.drawable.ic_nosee_pwd);
                }
                etPassword.setSelection(etPassword.getText().length());
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void loginInToApp() {
        final Bundle b = new Bundle();
        final Message msg = new Message();
        JSONObject object = new JSONObject();
        try {
            object.put("userLogin", userLoginType == 1 ? etPhone.getText().toString().trim() : etMail.getText().toString().trim());
            object.put("userPassword", etPassword.getText().toString().trim());
            String paramJson = object.toString();

            Type type = new TypeToken<LzyResponse<UserInfoBean>>() {}.getType();
            ServerApi.<LzyResponse<UserInfoBean>>getData(type, Urls.login, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading();
                        }
                    })//
                    .map(new Function<LzyResponse<UserInfoBean>, UserInfoBean>() {
                        @Override
                        public UserInfoBean apply(@NonNull LzyResponse<UserInfoBean> response) throws Exception {
                            return response.data;
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<UserInfoBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull UserInfoBean userInfoBean) {
                            if (null != userInfoBean) {
                                SPUtils.saveStringByKey(LoginActivity.this, Constants.UserId, userInfoBean.userId);
                                if (1 == userLoginType)
                                    SPUtils.saveStringByKey(LoginActivity.this, Constants.PhoneUserName, etPhone.getText().toString().trim());
                                else
                                    SPUtils.saveStringByKey(LoginActivity.this, Constants.MailUserName, etMail.getText().toString().trim());
                                insertUserInfoToDB(userInfoBean);
                                loginIntoJChat(userInfoBean);
                                showToast("登录成功");
                                EventBus.getDefault().post(new LoginEvent(true));
                                finish();
                            } else {
                                handler.sendEmptyMessage(2);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            dismissLoading();
                            handler.sendEmptyMessage(2);
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Logger.i(Logger.LOGTAG, "用户信息保存成功");
                    break;
                case 2:
                    showToast("登录失败");
                    break;
            }
        }
    };

    /**
     * 数据库保存用户信息
     *
     * @param model
     */
    private void insertUserInfoToDB(UserInfoBean model) {
        if (null != model) {
            UserInfoBean user = new UserInfoBean();
            user.setUserId(model.userId);
            user.setUserName(model.userName);
            user.setUserNickname(model.userNickname);
            user.setUserSex(model.userSex);
            user.setUserLogin(model.userLogin);
            user.setUserPassword(model.userPassword);
            user.setUserRegisterType(model.userRegisterType);
            user.setUserCountrynum(model.userCountrynum);
            user.setUserIntroduction(model.userIntroduction);
            user.setUserWechat(model.userWechat);
            user.setUserPic(model.userPic);
            user.setUserType(model.userType);
            user.setUserAuthentication(model.userAuthentication);
            user.setUserRealname(model.userRealname);
            user.setUserCard(model.userCard);
            user.setUserCardPic(model.userCardPic);
            user.setUserSatisfaction(model.userSatisfaction);
            user.setUserRecoveryrate(model.userRecoveryrate);
            user.setUserHobby(model.userHobby);
            user.setUserPhone(model.userPhone);
            user.setUserSesameCredit(model.userSesameCredit);
            user.setUserJChatAppKey(model.userJChatAppKey);
            user.setUserJChatName(model.userJChatName);
            user.saveOrUpdateAsync("userId = ?", model.getUserId()).listen(new SaveCallback() {
                @Override
                public void onFinish(boolean success) {
                    handler.sendEmptyMessage(1);
                }
            });
        }
    }

    private void loginIntoJChat(final UserInfoBean model){
        JMessageClient.login("DeYou"+"_"+ model.getUserLogin().split("@")[0], model.getUserPassword(), new BasicCallback() {
            @Override
            public void gotResult(final int status, String desc) {
                if (status == 0) {
                    String username = JMessageClient.getMyInfo().getUserName();
                    String appKey = JMessageClient.getMyInfo().getAppKey();
                    model.setUserJChatName(username);
                    model.setUserJChatAppKey(appKey);
                    model.saveOrUpdateAsync("userId = ?", model.getUserId()).listen(new SaveCallback() {
                        @Override
                        public void onFinish(boolean success) {
                            handler.sendEmptyMessage(1);
                        }
                    });
                } else {
                    Logger.i(Logger.LOGTAG + "JChat", desc);
                }
            }
        });
    }
}
